package com.logistic.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logistic.server.common.constant.Constants;
import com.logistic.server.common.enums.IsDelEnum;
import com.logistic.server.common.exception.BaseException;
import com.logistic.server.common.utils.SecurityUtils;
import com.logistic.server.entity.common.PageRequest;
import com.logistic.server.entity.common.PageResponse;
import com.logistic.server.entity.common.WebUserToken;
import com.logistic.server.entity.pojo.*;
import com.logistic.server.mapper.*;
import com.logistic.server.service.ISysLoginService;
import com.logistic.server.service.ISysUserService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author swen
 * @since 2021-10-26
 */
@Service
@Transactional
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private SysUserPostMapper userPostMapper;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Resource
    private SysPostMapper postMapper;

    @Resource
    @Lazy
    private ISysLoginService loginService;

    /**
     * 通过openid取用户信息
     * @param openid openid
     * @return user
     */
    @Override
    public SysUser findByOpenId(String openid) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getOpenid, openid);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 分页查询用户列表
     * @param user 用户信息
     * @param pageRequest 分页
     * @return list
     */
    @Override
    public PageResponse<SysUser> selectPageUserList(SysUser user, PageRequest pageRequest) {
        IPage<SysUser> page = new Page<>(pageRequest.getPageIndex(), pageRequest.getPageSize());
        IPage<SysUser> result = baseMapper.selectPageUserList(page, user);
        return PageResponse.<SysUser>builder().total(result.getTotal()).list(result.getRecords()).build();
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @param pageRequest 分页
     * @return 用户信息集合信息
     */
    @Override
    public PageResponse<SysUser> selectAllocatedList(SysUser user, PageRequest pageRequest) {
        IPage<SysUser> page = new Page<>(pageRequest.getPageIndex(), pageRequest.getPageSize());
        IPage<SysUser> result = baseMapper.selectAllocatedList(page, user);
        return PageResponse.<SysUser>builder().total(result.getTotal()).list(result.getRecords()).build();
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @param pageRequest 分页
     * @return 用户信息集合信息
     */
    @Override
    public PageResponse<SysUser> selectUnallocatedList(SysUser user, PageRequest pageRequest) {
        IPage<SysUser> page = new Page<>(pageRequest.getPageIndex(), pageRequest.getPageSize());
        IPage<SysUser> result = baseMapper.selectUnallocatedList(page, user);
        return PageResponse.<SysUser>builder().total(result.getTotal()).list(result.getRecords()).build();
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return baseMapper.selectUserById(userId);
    }

    /**
     * 通过用户名字查询用户
     * @param userName 用户名字
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUser::getUserName, userName);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     */
    @Override
    public void updateUserStatus(SysUser user) {
        baseMapper.updateById(user);
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (ObjectUtil.isNotEmpty(user.getUserId()) && user.isAdmin()) {
            throw new BaseException("不允许操作超级管理员用户");
        }
    }

    /**
     * 添加用户
     * @param user 用户信息
     */
    @Override
    public void insertUser(SysUser user) {
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateTime(new Date());
        user.setPassword(SecurityUtils.password(user.getPassword()));
        user.setDelFlag(IsDelEnum.FALSE.getValue());
        // 新增用户信息
        baseMapper.insert(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
    }

    /**
     * 删除用户
     * @param ids ids
     */
    @Override
    public void deleteUser(List<String> ids) {
        for (String userId : ids) {
            checkUserAllowed(new SysUser(Long.parseLong(userId)));
        }
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getUserId, ids));
        // 删除用户与岗位
        userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getUserId, ids));
        baseMapper.deleteBatchIds(ids);
    }

    /**
     * 修改用户
     * @param user 用户
     */
    @Override
    public void updateUser(SysUser user) {
        this.checkUserAllowed(user);
        if (StrUtil.isNotEmpty(user.getPhonenumber())
                && Constants.NOT_UNIQUE.equals(this.checkPhoneUnique(user))) {
            throw new BaseException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StrUtil.isNotEmpty(user.getEmail())
                && Constants.NOT_UNIQUE.equals(this.checkEmailUnique(user))) {
            throw new BaseException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        // 删除用户与角色关联
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, user.getUserId()));
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.delete(new LambdaQueryWrapper<SysUserPost>().eq(SysUserPost::getUserId, user.getUserId()));
        // 新增用户与岗位管理
        insertUserPost(user);
        // 修改用户
        baseMapper.updateById(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));
        insertUserRole(userId, roleIds);
    }

    /**
     * 根据用户ID查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (SysRole role : list) {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StrUtil.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 根据用户ID查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuilder idsStr = new StringBuilder();
        for (SysPost post : list) {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StrUtil.isNotEmpty(idsStr.toString())) {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 个人信息修改
     * @param user 用户
     */
    @Override
    public void updateProfile(SysUser user) {
        if (StrUtil.isNotEmpty(user.getPhonenumber())
                && Constants.NOT_UNIQUE.equals(this.checkPhoneUnique(user))) {
            throw new BaseException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StrUtil.isNotEmpty(user.getEmail())
                && Constants.NOT_UNIQUE.equals(this.checkEmailUnique(user))) {
            throw new BaseException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(null);
        baseMapper.updateById(user);
        WebUserToken webUserToken = SecurityUtils.getLoginUser();
        assert webUserToken != null;
        BeanUtil.copyProperties(user, webUserToken);
        loginService.refreshToken(webUserToken);
    }

    /**
     * 修改密码
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     */
    @Override
    public void updatePwd(String oldPassword, String newPassword) {
        WebUserToken webUserToken = SecurityUtils.getLoginUser();
        assert webUserToken != null;
        String userName = webUserToken.getUserName();
        String password = webUserToken.getPassword();
        if (!SecurityUtils.matchesPassword(SecurityUtils.password(oldPassword), password)) {
            throw new BaseException("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(SecurityUtils.password(newPassword), password)) {
            throw new BaseException("新密码不能与旧密码相同");
        }
        String dpassword = SecurityUtils.password(newPassword);
        baseMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                        .set(SysUser::getPassword, dpassword)
                        .eq(SysUser::getUserName, userName));
        webUserToken.setPassword(dpassword);
        loginService.refreshToken(webUserToken);
    }

    /**
     * 修改头像
     * @param avatar 头像
     */
    @Override
    public void updateUserAvatar(String avatar) {
        WebUserToken webUserToken = SecurityUtils.getLoginUser();
        assert webUserToken != null;
        baseMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                        .set(SysUser::getAvatar, avatar)
                        .eq(SysUser::getUserName, webUserToken.getUserName()));
        webUserToken.setAvatar(avatar);
        loginService.refreshToken(webUserToken);
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (ObjectUtil.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                list.forEach(e -> {
                    userPostMapper.insert(e);
                });
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (ObjectUtil.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                list.forEach(e -> {
                    userRoleMapper.insert(e);
                });
            }
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (ObjectUtil.isNotNull(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                list.forEach(e -> {
                    userRoleMapper.insert(e);
                });
            }
        }
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return str
     */
    public String checkPhoneUnique(SysUser user) {
        long userId = ObjectUtil.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = getOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUserId, SysUser::getPhonenumber)
                .eq(SysUser::getPhonenumber, user.getPhonenumber()).last("limit 1"));
        if (ObjectUtil.isNotNull(info) && info.getUserId() != userId) {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return str
     */
    public String checkEmailUnique(SysUser user) {
        long userId = ObjectUtil.isNotEmpty(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = getOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUserId, SysUser::getEmail)
                .eq(SysUser::getEmail, user.getEmail()).last("limit 1"));
        if (ObjectUtil.isNotNull(info) && info.getUserId() != userId) {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

}
